import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import {Form, Icon, Input, Button, message} from 'antd';
import axios from "axios";

class Register extends PureComponent {
  static PropTypes = {
    handleClick: PropTypes.func.isRequired
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        axios.get('http://localhost:8080/api/register', {
          params: {
            username: values.userName,
            password: values.password
          }
        }).then((res) => {
            if (res.data.code === 200) {
              message.success(res.data.msg);
            }else {
              message.error(res.data.msg);
            }
          })
          .catch((err) => {
            message.error('请求异常，请稍后重试');
          })
      }
    });
  };

  login = () => {
    this.props.handleClick('login');
  };

  render() {
    const { getFieldDecorator } = this.props.form;

    return (
      <Form onSubmit={this.handleSubmit}>
        <Form.Item>
          {getFieldDecorator('userName', {
            rules: [{ required: true, message: '请输入用户名！' }],
          })(
            <Input style={{height: 40}} prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('password', {
            rules: [{ required: true, message: '请输入密码！' }],
          })(
            <Input style={{height: 40}} prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" style={{width: '100%', height: 40}}>
            注册
          </Button>
          注册成功了？ <a href="javascript:;" onClick={() => {this.login()}}>现在就登录！</a>
        </Form.Item>
      </Form>
    );
  }
}

export default Form.create()(Register);